import OSS from 'ali-oss'
import { createUploadCatalogue } from '@/utils/utils'

let client = new OSS({
  // Bucket所在地域
  region: 'oss-cn-shanghai',
  accessKeyId: 'LTAI5tBiXeF4s5vYvEQWLuHw',
  accessKeySecret: 'vFKbZWPZyg9lj3kj7ia7N5Omoen3jg',
  // 填写Bucket名称
  bucket: 'leyi-blog',
})

let tempCheckpoint

async function multipartUpload (file, type) {
  try {
    let path = createUploadCatalogue(type, file.name)
    if (typeof path === 'string') {
      const result = await client.multipartUpload(path, file, {
        progress: function (p, checkpoint) {
          tempCheckpoint = checkpoint
          console.log(p, tempCheckpoint)
        },
        parallel: 4,
        partSize: 1024 * 1024,
        mime: file.type,
      })
      if (result.res.status === 200) {
        console.log(result)
        return Promise.resolve({
          url: `http://leyi-blog.oss-cn-shanghai.aliyuncs.com/${result.name}`
        })
      }
    }
  } catch (e) {
    console.log(e)
  }
}

const getOssPreviewUrl = (originUrl) => {
  let filename = originUrl.split('/').pop() || ''
  const response = {
    'content-disposition': 'inline'
  }

  return client.signatureUrl(filename, { response })
}

export {
  multipartUpload,
  getOssPreviewUrl,
}